<template>
	<view class="headerbar">
		<scroll-view enable-flex scroll-x class="navbar" scroll-with-animation :scroll-left="scrollLeft">
			<view 
			class="nav-item" 
			v-for="(item, index) in tabs" 
			:key="item.id" 
			@tap="tabSelect" 
			:data-id="item.id"
			>
				<view 
				class="nav-text" 
				:class="{'tab-on': index === tabCur}"
				>
				{{item.name}}
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: "MyHeader",
		data() {
			return {
				tabCur: 0, // 默认选中
				scrollLeft: 0, // 初始化滚动位置
				tabs: [
					{ name: '推荐', id: 0 },
					{ name: '免费', id: 1 },
					{ name: '男生', id: 2 },
					{ name: '女生', id: 3 },
					{ name: '出版', id: 4 },
					{ name: '听书', id: 5 },
					{ name: '漫画', id: 6 },
					{ name: '知识', id: 7 },
					{ name: '故事', id: 8 },
					{ name: '视频', id: 9 },
				],
			};
		},
		methods: {
			tabSelect(e) {
				const selectedId = e.currentTarget.dataset.id;
				this.tabCur = selectedId;
				this.scrollLeft = (selectedId - 2) * 180;
				this.$emit('tab-change', selectedId); // 触发事件给父组件
			}
		}
	}
</script>

<style>
	/* 导航栏布局相关 */
	.navbar {
		width: 100%;
		height: 80rpx;
		white-space: nowrap;
		display: flex;
		box-sizing: border-box;
		background: #fff;
		align-items: center;
		margin-top: 20rpx;
		margin-bottom: 10rpx;
	}

	.nav-item {
		padding-left: 25rpx;
		padding-right: 25rpx;
		height: 100%;
		display: inline-block;
		font-size: 28rpx;
	}

	.nav-text {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		letter-spacing: 4rpx;
		box-sizing: border-box;
	}

	.tab-on {
		color: #ff5e48;
		font-size: 36rpx !important;
		font-weight: bold;
		border-bottom: 6rpx solid #ff5e48 !important;
	}
</style>
